package deng.hibernate.examples;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class EntitytManagerMain {
	
	private EntityManager entityManager;
	
	private boolean runInsertData = true;
	
	public static void main(String[] args) {
		new EntitytManagerMain().run();
	}

	public void run() {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("testdb");
		entityManager = emf.createEntityManager();
		EntityTransaction tx = entityManager.getTransaction();
		try {
			tx.begin();
			runExample();
			tx.commit();
		} catch (Throwable e) {
			if (tx.isActive()) {
				tx.rollback();
			}
			throw new RuntimeException(e);
		} finally {
			entityManager.close();
			emf.close();
		}
	}

	private void runExample() {
		if (runInsertData) {
			runCreateData();
			entityManager.flush();
			entityManager.clear();
		}
		runQuery();
	}
	
	private void runCreateData() {
		for (int i = 0; i < 10; i++) {
			Simple m = new Simple();
			m.setName("Hello" + i + " World");
			entityManager.persist(m);
		}
	}

	private void runQuery() {
		printQueryResult("from Simple");
	}

	public void printQueryResult(String queryString) {
		List<?> list = entityManager.createQuery(queryString).getResultList();
		for (Object object : list) {
			System.out.println(object);
		}
		System.out.println("Size= " + list.size());
	}
	
}
